package com.marui.eight.complatefuture;

import com.marui.eight.complatefuture.help.MyTask;

import java.util.concurrent.*;

/**
 * @author marui
 * @version 1.0
 * @date 2021/6/13 10:53 上午
 * @since 1.0
 */
public class Demo1 {
    public static void main(String[] args) throws Exception {
        MyTask task = new MyTask();

        method1(task);
        System.out.println("---------------------------------华丽分割---------------------------------");
        method2();
    }

    private static void method1(MyTask task) throws Exception {
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<String> result = executor.submit(task);
        executor.shutdown();
        System.out.println("task运行结果" + result.get());
        System.out.println("end");
    }


    private static void method2() throws Exception {
        //supplyAsync内部使用ForkJoinPool线程池执行任务
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            //模拟执行耗时任务
            System.out.println("task doing...");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //返回结果
            return "100";
        }).whenComplete((v, r) -> {
            System.out.println("计算结果是: " + v);
        });
        //CompletableFuture里使用的线程池里的线程默认是daemon的。main线程结束后，整个程序也
        //结束了，这里将main线程join后任务里的代码才可以执行完
        System.out.println("end");
        Thread.currentThread().join();
    }


}
